package Models;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Hashtable;

public class DBSupport {
	private static DBSupport instance = null;
	private Hashtable<String, User> users;
	private Hashtable<Integer, Equipment> equipment;

	private DBSupport() {
		users = new Hashtable<String, User>();
		equipment = new Hashtable<Integer, Equipment>();
	}

	public static DBSupport getDBSupportInstance() {
		if (instance == null) {
			instance = new DBSupport();
		}
		return instance;
	}

	public void putEquipment(Equipment e) {
		equipment.put(e.getID(), e);
	}

	public Equipment getEquipment(int ID) {
		return equipment.get(ID);
	}

	public void removeEquipment(int ID) {
		equipment.remove(ID);
	}

	public void putUser(User user) {
		users.put(user.getNetID().toLowerCase(), user);
	}

	public User getUser(String netID) {
		return users.get(netID.toLowerCase());
	}

	public void removeUser(String netID) {
		users.remove(netID);
	}

	public void readFile(String userLoc, String equipLoc) {
		try {
			InputStream inFile = new FileInputStream(userLoc);
			ObjectInputStream in = new ObjectInputStream(inFile);
			User u = (User) in.readObject();
			while(u != null){
				users.put(u.getNetID(), u);
				try{
					u = (User) in.readObject();
				} catch(IOException e){
					u = null;
				}
			}


			inFile = new FileInputStream(equipLoc);
			in = new ObjectInputStream(inFile);
			Equipment e = (Equipment) in.readObject();
			while(e != null){
				equipment.put(e.getID(), e);
				try{
					e = (Equipment) in.readObject();
				} catch(IOException a){
					e = null;
				}
			}
		} catch (IOException e) {
		} catch (ClassNotFoundException e) {
		}
	}

	public void writeFile(String userLoc, String equipLoc) {
		try {
			OutputStream outFile = new FileOutputStream(userLoc);
			ObjectOutputStream out = new ObjectOutputStream(outFile);
			ArrayList<User> u = new ArrayList<User>(users.values());
			for (int i = 0; i < users.size(); i++) {
				out.writeObject(u.get(i));
			}

			outFile = new FileOutputStream(equipLoc);
			out = new ObjectOutputStream(outFile);
			ArrayList<Equipment> e = new ArrayList<Equipment>(equipment.values());
			for (int i = 0; i < equipment.size(); i++) {
				out.writeObject(e.get(i));
			}
		} catch (FileNotFoundException e) {
		} catch (IOException e) {
		}
	}

	public Collection<Equipment> getAllEquipment() {
		return equipment.values();
	}

}
